<template>
  <div class="care-category">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="类别名称">
          <el-input v-model="searchForm.name" placeholder="请输入类别名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="启用" value="enabled" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAdd">新增类别</el-button>
      <el-button type="success" @click="handleBatchEnable" :disabled="!selectedRows.length">
        批量启用
      </el-button>
      <el-button type="danger" @click="handleBatchDisable" :disabled="!selectedRows.length">
        批量禁用
      </el-button>
    </div>

    <!-- 类别列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        row-key="id"
        :tree-props="{ children: 'children' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="类别名称" min-width="200">
          <template #default="{ row }">
            <span v-if="row.level === 1">{{ row.name }}</span>
            <span v-else class="sub-category">{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="类别编码" width="120" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'enabled' ? 'success' : 'info'">
              {{ row.status === 'enabled' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="serviceCount" label="服务数量" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleAddSub(row)" v-if="row.level === 1">
              添加子类
            </el-button>
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button 
              :type="row.status === 'enabled' ? 'danger' : 'success'"
              link 
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 'enabled' ? '禁用' : '启用' }}
            </el-button>
            <el-button type="primary" link @click="handleManageServices(row)">
              管理服务
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDelete(row)"
              v-if="!row.children?.length"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 类别表单对话框 -->
    <el-dialog
      v-model="formDialogVisible"
      :title="formData.id ? '编辑类别' : (formData.parentId ? '添加子类' : '新增类别')"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="上级类别" v-if="!formData.parentId">
          <el-select v-model="formData.parentId" placeholder="请选择" clearable>
            <el-option
              v-for="item in parentCategories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类别名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入类别名称" />
        </el-form-item>
        <el-form-item label="类别编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入类别编码" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="enabled">启用</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-upload
            class="category-icon-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleIconSuccess"
            :before-upload="beforeIconUpload"
          >
            <img v-if="formData.icon" :src="formData.icon" class="category-icon" />
            <el-icon v-else class="category-icon-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入类别描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 服务管理对话框 -->
    <el-dialog
      v-model="serviceDialogVisible"
      :title="`${currentCategory.name} - 服务管理`"
      width="800px"
    >
      <div class="service-management">
        <!-- 服务列表 -->
        <div class="service-list">
          <div class="service-header">
            <h3>服务列表</h3>
            <el-button type="primary" @click="handleAddService">添加服务</el-button>
          </div>
          <el-table
            :data="serviceList"
            border
            style="width: 100%"
          >
            <el-table-column prop="name" label="服务名称" min-width="150" />
            <el-table-column prop="price" label="价格" width="120">
              <template #default="{ row }">
                ¥{{ row.price.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="duration" label="时长" width="100">
              <template #default="{ row }">
                {{ row.duration }}分钟
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'enabled' ? 'success' : 'info'">
                  {{ row.status === 'enabled' ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleEditService(row)">
                  编辑
                </el-button>
                <el-button 
                  :type="row.status === 'enabled' ? 'danger' : 'success'"
                  link 
                  @click="handleToggleServiceStatus(row)"
                >
                  {{ row.status === 'enabled' ? '禁用' : '启用' }}
                </el-button>
                <el-button type="danger" link @click="handleDeleteService(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 服务表单对话框 -->
    <el-dialog
      v-model="serviceFormDialogVisible"
      :title="serviceForm.id ? '编辑服务' : '添加服务'"
      width="500px"
    >
      <el-form
        ref="serviceFormRef"
        :model="serviceForm"
        :rules="serviceFormRules"
        label-width="100px"
      >
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="serviceForm.name" placeholder="请输入服务名称" />
        </el-form-item>
        <el-form-item label="服务价格" prop="price">
          <el-input-number
            v-model="serviceForm.price"
            :min="0"
            :precision="2"
            :step="0.01"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="服务时长" prop="duration">
          <el-input-number
            v-model="serviceForm.duration"
            :min="0"
            :step="5"
            style="width: 200px"
          />
          <span class="unit">分钟</span>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="serviceForm.status">
            <el-radio label="enabled">启用</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="服务图片" prop="images">
          <el-upload
            class="service-image-uploader"
            :action="uploadUrl"
            list-type="picture-card"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            :on-remove="handleImageRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="服务描述" prop="description">
          <el-input
            v-model="serviceForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入服务描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="serviceFormDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleServiceSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getMerchantCareCategoryList,
  createMerchantCareCategory,
  updateMerchantCareCategory,
  deleteMerchantCareCategory,
  batchUpdateMerchantCareCategoryStatus,
  getMerchantCareServiceList,
  createMerchantCareService,
  updateMerchantCareService,
  deleteMerchantCareService,
  updateMerchantCareServiceStatus
} from '@/api/merchant'

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 分页
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])

// 表单对话框
const formDialogVisible = ref(false)
const formRef = ref(null)
const formData = reactive({
  id: '',
  parentId: '',
  name: '',
  code: '',
  sort: 0,
  status: 'enabled',
  icon: '',
  description: ''
})

// 服务管理对话框
const serviceDialogVisible = ref(false)
const currentCategory = ref({})
const serviceList = ref([])

// 服务表单对话框
const serviceFormDialogVisible = ref(false)
const serviceFormRef = ref(null)
const serviceForm = reactive({
  id: '',
  categoryId: '',
  name: '',
  price: 0,
  duration: 30,
  status: 'enabled',
  images: [],
  description: ''
})

// 上传相关
const uploadUrl = '/api/merchant/upload'
const beforeIconUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传图标只能是图片格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传图标大小不能超过 2MB!')
  }
  return isImage && isLt2M
}

const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('上传图片只能是图片格式!')
  }
  if (!isLt5M) {
    ElMessage.error('上传图片大小不能超过 5MB!')
  }
  return isImage && isLt5M
}

const handleIconSuccess = (response) => {
  formData.icon = response.url
}

const handleImageSuccess = (response) => {
  serviceForm.images.push(response.url)
}

const handleImageRemove = (file) => {
  const index = serviceForm.images.indexOf(file.url)
  if (index !== -1) {
    serviceForm.images.splice(index, 1)
  }
}

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入类别名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入类别编码', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const serviceFormRules = {
  name: [{ required: true, message: '请输入服务名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入服务价格', trigger: 'blur' }],
  duration: [{ required: true, message: '请输入服务时长', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 获取类别列表
const getCategoryList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: page.current,
      size: page.size
    }
    const { data } = await getMerchantCareCategoryList(params)
    tableData.value = data.list
    page.total = data.total
  } catch (error) {
    console.error('获取类别列表失败:', error)
    ElMessage.error('获取类别列表失败')
  } finally {
    loading.value = false
  }
}

// 获取服务列表
const getServiceList = async (categoryId) => {
  try {
    const { data } = await getMerchantCareServiceList(categoryId)
    serviceList.value = data
  } catch (error) {
    console.error('获取服务列表失败:', error)
    ElMessage.error('获取服务列表失败')
  }
}

// 搜索
const handleSearch = () => {
  page.current = 1
  getCategoryList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 选择行变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 新增类别
const handleAdd = () => {
  Object.keys(formData).forEach(key => {
    formData[key] = key === 'status' ? 'enabled' : ''
  })
  formData.sort = 0
  formDialogVisible.value = true
}

// 添加子类
const handleAddSub = (row) => {
  Object.keys(formData).forEach(key => {
    formData[key] = key === 'status' ? 'enabled' : ''
  })
  formData.parentId = row.id
  formData.sort = 0
  formDialogVisible.value = true
}

// 编辑类别
const handleEdit = (row) => {
  Object.assign(formData, row)
  formDialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    if (formData.id) {
      await updateMerchantCareCategory(formData.id, formData)
      ElMessage.success('更新成功')
    } else {
      await createMerchantCareCategory(formData)
      ElMessage.success('创建成功')
    }
    formDialogVisible.value = false
    getCategoryList()
  } catch (error) {
    console.error('提交表单失败:', error)
  }
}

// 切换状态
const handleToggleStatus = async (row) => {
  try {
    const newStatus = row.status === 'enabled' ? 'disabled' : 'enabled'
    await updateMerchantCareCategory(row.id, { status: newStatus })
    ElMessage.success(`${newStatus === 'enabled' ? '启用' : '禁用'}成功`)
    getCategoryList()
  } catch (error) {
    console.error('切换状态失败:', error)
  }
}

// 批量启用
const handleBatchEnable = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要启用的类别')
    return
  }
  try {
    const ids = selectedRows.value.map(row => row.id)
    await batchUpdateMerchantCareCategoryStatus(ids, 'enabled')
    ElMessage.success('批量启用成功')
    getCategoryList()
  } catch (error) {
    console.error('批量启用失败:', error)
  }
}

// 批量禁用
const handleBatchDisable = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要禁用的类别')
    return
  }
  try {
    const ids = selectedRows.value.map(row => row.id)
    await batchUpdateMerchantCareCategoryStatus(ids, 'disabled')
    ElMessage.success('批量禁用成功')
    getCategoryList()
  } catch (error) {
    console.error('批量禁用失败:', error)
  }
}

// 删除类别
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该类别吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantCareCategory(row.id)
    ElMessage.success('删除成功')
    getCategoryList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除类别失败:', error)
    }
  }
}

// 管理服务
const handleManageServices = async (row) => {
  currentCategory.value = row
  serviceDialogVisible.value = true
  await getServiceList(row.id)
}

// 添加服务
const handleAddService = () => {
  Object.keys(serviceForm).forEach(key => {
    serviceForm[key] = key === 'status' ? 'enabled' : ''
  })
  serviceForm.categoryId = currentCategory.value.id
  serviceForm.price = 0
  serviceForm.duration = 30
  serviceForm.images = []
  serviceFormDialogVisible.value = true
}

// 编辑服务
const handleEditService = (row) => {
  Object.assign(serviceForm, row)
  serviceFormDialogVisible.value = true
}

// 提交服务表单
const handleServiceSubmit = async () => {
  if (!serviceFormRef.value) return
  
  try {
    await serviceFormRef.value.validate()
    if (serviceForm.id) {
      await updateMerchantCareService(serviceForm.id, serviceForm)
      ElMessage.success('更新成功')
    } else {
      await createMerchantCareService(serviceForm)
      ElMessage.success('创建成功')
    }
    serviceFormDialogVisible.value = false
    getServiceList(currentCategory.value.id)
  } catch (error) {
    console.error('提交服务表单失败:', error)
  }
}

// 切换服务状态
const handleToggleServiceStatus = async (row) => {
  try {
    const newStatus = row.status === 'enabled' ? 'disabled' : 'enabled'
    await updateMerchantCareServiceStatus(row.id, newStatus)
    ElMessage.success(`${newStatus === 'enabled' ? '启用' : '禁用'}成功`)
    getServiceList(currentCategory.value.id)
  } catch (error) {
    console.error('切换服务状态失败:', error)
  }
}

// 删除服务
const handleDeleteService = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该服务吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantCareService(row.id)
    ElMessage.success('删除成功')
    getServiceList(currentCategory.value.id)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除服务失败:', error)
    }
  }
}

// 分页大小变化
const handleSizeChange = (val) => {
  page.size = val
  getCategoryList()
}

// 页码变化
const handleCurrentChange = (val) => {
  page.current = val
  getCategoryList()
}

onMounted(() => {
  getCategoryList()
})
</script>

<style lang="scss" scoped>
.care-category {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .action-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
  }

  .table-card {
    .sub-category {
      padding-left: 20px;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .category-icon-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }

    .category-icon-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      text-align: center;
      line-height: 100px;
    }

    .category-icon {
      width: 100px;
      height: 100px;
      display: block;
    }
  }

  .service-management {
    .service-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h3 {
        margin: 0;
        font-size: 16px;
        color: #303133;
      }
    }
  }

  .service-image-uploader {
    :deep(.el-upload--picture-card) {
      width: 100px;
      height: 100px;
      line-height: 100px;
    }
  }

  .unit {
    margin-left: 10px;
    color: #909399;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 